<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/hello' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="24">

          <!-- 搜索区域 -->
          <el-input placeholder="请输入内容" v-model="getUser.query" clearable @clear="getUsers()">
            <el-button slot="append" icon="el-icon-search" @click="getUsers()"></el-button>
          </el-input>

          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="openAdd">添加用户</el-button>
      </el-row>
      <el-row :gutter="24">
        <el-table :data="tableData" border stripe>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="statChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scoped">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUser(scoped.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scoped.row)"
              ></el-button>
              <el-button
                type="primary"
                icon="el-icon-s-tools"
                size="mini"
                title="设置角色"
                @click="setRoles(scoped.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页模块 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="getUser.pagenum"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="getUser.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-row>
    </el-card>
    <!-- 弹出框模块 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- 添加用户表单 -->
      <el-form
        :model="addForm"
        status-icon
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="text" v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑表单 -->
    <el-dialog title="修改用户信息" :visible.sync="editVisible" width="50%">
      <!-- 编辑用户表单 -->
      <el-form
        :model="editForm"
        status-icon
        :rules="addFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input type="text" v-model="user" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="text" v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色弹框 Form -->
    <el-dialog title="设置角色" :visible.sync="editEolesVisible">
      <el-form>
        <p> 用户名：{{user}}</p>
        <p> 当前角色：{{roles}}</p>
        <el-form-item label="角色设置：" >
          <el-select v-model="newRolesId" placeholder="请选择角色">
            <el-option :label="e.roleName" :value="e.id" v-for="e in rolesData" :key="e.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editEolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      let rul = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]* {2}[\w])?/
      if (!rul.test(value)) return callback(new Error('邮箱不合法'))
      callback()
    }
    var validateMobile = (rule, value, callback) => {
      let rul = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/
      if (!rul.test(value)) return callback(new Error('手机号不合法'))
      callback()
    }
    return {
      flag: 'edit', // 标志符 edit：编辑用户信息 set：设置用户角色
      getUser: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      tableData: [], // user列表
      rolesData: [], // roles列表
      search: '',
      // 控制添加用户对话框
      dialogVisible: false,
      // 编辑对话框
      editVisible: false,
      // 设置角色对话框
      editEolesVisible: false,
      // 添加表单
      addForm: {
        password: '',
        username: '',
        email: '',
        mobile: ''
      },

      id: '',
      user: '',
      roles: '', // 当前设置的角色
      newRolesId: '', // 设置新角色id
      // 编辑表单信息
      editForm: {
        email: '',
        mobile: ''
      },
      // 验证用户名是否合法
      addFormRules: {
        username: [{ required: true, message: '请输入登录名称', trigger: 'blur' }, { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }],
        // 验证密码是否合法
        password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }, { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }],
        email: [{ validator: validateEmail, required: true, trigger: 'blur' }],
        mobile: [{ validator: validateMobile, required: true, trigger: 'blur' }]
      }

    }
  },
  methods: {
    // 请求用户列表
    async getUsers() {
      // const { data: res } = await this.$http.get(`users`, {
      //   params: this.getUser
      // })
      let { data: res } = await this.$Http.getUsers({
        params: this.getUser
      })
      this.total = res.data.total
      this.tableData = res.data.users
    },
    // 设置pagesize
    handleSizeChange(val) {
      this.getUser.pagesize = val
      this.getUsers()
    },
    // 设置当前页
    handleCurrentChange(val) {
      this.getUser.pagenum = val
      this.getUsers()
    },
    // 修改状态请求
    async statChange(val) {
      // const { data: res } = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
      const { data: res } = await this.$Http.setStatus(val.id, val.mg_state)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getUsers()
    },
    // 点击打开添加窗口
    openAdd() {
      this.dialogVisible = true
      // 重置表单
      if (this.$refs.addFormRef) {
        this.$refs.addFormRef.resetFields()
      }
    },
    // 添加用户操作
    sendAdd() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.dialogVisible = false
        // let { data: res } = await this.$http.post(`users`, this.addForm)
        let { data: res } = await this.$Http.addUsers(this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUsers()
      })
    },
    // 点击编辑用户信息
    editUser(val) {
      this.editForm.email = val.email
      this.editForm.mobile = val.mobile
      this.user = val.username
      this.id = val.id
      this.editVisible = true
      if (this.$refs.editFormRef) {
        this.$refs.editFormRef.resetFields()
      }
    },
    // 点击设置角色
    async setRoles(val) {
      this.editEolesVisible = true
      this.id = val.id
      this.user = val.username
      // console.log(val);
      this.roles = val.role_name
      let { data: res } = await this.$Http.getAllRoles()
      this.rolesData = res.data
    },
    // 点击编辑完成
    sendEdit() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // let {data:res} = await this.$http.put(`users/${this.id}`,this.editForm)
        let { data: res } = await this.$Http.editUsers(this.id, this.editForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editVisible = false
        this.getUsers()
      })
    },
    // 点击完成角色设置
    async sendRoles() {
      this.editEolesVisible = false
      let { data: res } = await this.$Http.setNewRoles(this.id, this.newRolesId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.newRolesId = ''
      this.getUsers()
    },
    // 点击删除
    deleteUser(val) {
      this.$confirm(`此操作将永久删除用户:  ${val.username}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // let {data:res} = await this.$http.delete(`users/${val.id}`)
          let { data: res } = await this.$http.delete(val.id)
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUsers()
        })
        .catch(() => {
          this.$message.info('已取消删除!')
        })
    }
  },
  created() {
    this.getUsers()
  }
}
</script>

 <style lang="less" scoped>
.el-table {
  width: 100%;
  .el-table td,
  .el-table th {
    text-align: center !important;
  }
}
.el-input {
  width: 50%;
  margin-right: 20px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}
</style>
